#include <STC89C5xRC.H>
#include "timer0.h"
#include "Int0.h"

//红外模块

unsigned int ir_time;
unsigned char ir_state;

unsigned char ir_data[4];
unsigned char ir_pdata;

unsigned char ir_dataflag;
unsigned char ir_repeatflag;
unsigned char ir_address;
unsigned char ir_command;

void ir_init()
{
	time0_init1();
	int0_init();
}

unsigned char ir_getdataflag()
{
	if(ir_dataflag)
	{
		ir_dataflag=0;
		return 1;
	}
	return 0;
}
	
unsigned char ir_getrepeatflag()
{
	if(ir_repeatflag)
	{
		ir_repeatflag=0;
		return 1;
	}
	return 0;
}

unsigned char ir_getaddress()
{
	return ir_address;
}

unsigned char ir_getcommand()
{
	return ir_command;
}



void Int0_Routine(void)    interrupt 0
{
	if(ir_state==0)
	{
		timer0_setcounter(0);
		timer0_run(1);
		ir_state=1;
	}
	else if(ir_state==1)
	{
		ir_time=timer0_getcounter();
		timer0_setcounter(0);
		if(ir_time>12442-500 && ir_time<12442+500)
		{
			ir_state=2;
		}
		else if(ir_time>10368-500 && ir_time<10368+500)
		{
			ir_repeatflag=1;
			timer0_run(0);
			ir_state=0;
		}
		else
		{
			ir_state=1;
		}
	}
	else if(ir_state==2)
	{
		ir_time=timer0_getcounter();
		timer0_setcounter(0);
		if(ir_time>1016-500 && ir_time<1016+500)
		{
			ir_data[ir_pdata/8]&=~(0x01<<(ir_pdata%8));
			ir_pdata++;
		}
		else if(ir_time>2074-500 && ir_time<2074+500)
		{
			ir_data[ir_pdata/8]|=(0x01<<(ir_pdata%8));
			ir_pdata++;
		}
		else
		{
			ir_pdata=0;
			ir_state=1;
		}
		if(ir_pdata>=32)
		{
			ir_pdata=0;
			if((ir_data[0] == ~ir_data[1]) && (ir_data[2] == ~ir_data[3]))
			{
				ir_address=ir_data[0];
				ir_command=ir_data[2];
				ir_dataflag=1;
			}
			timer0_run(0);
			ir_state=0;
		}

	}
	
}